<template>
  <view class="end flex flex-col justify-center">
    <NavigationBar navigation-title="完成课程" :go-back="goBack" />
    <image class="end-bg" src="https://app5.shuguostar.cn/imgs/images/answer/bg.png" />
    <image class="end-id" src="https://app5.shuguostar.cn/imgs/images/answer/IP_4.png" />

    <view class="end-content flex flex-col">
      <image class="text-bg" src="https://app5.shuguostar.cn/imgs/images/answer/text_bg.png" />

      <view class="end-title flex flex-col">
        <text>恭喜你</text>
        <text>又读完一本书</text>
      </view>

      <view class="end-wrap flex-1">
        <view class="end-info flex items-center justify-between">
          <text class="label flex-1">
            阅读内容
          </text>
          <text class="value">
            {{ `《${detail?.bookName}》` }}
          </text>
        </view>
        <view class="end-info flex items-center justify-between">
          <text class="label flex-1">
            阅读时间
          </text>
          <text class="value">
            {{ `${detail?.startDate}至${detail?.endDate}` }}
          </text>
        </view>

        <view class="end-item item-top">
          <view class="item-title flex items-center">
            <image class="title-icon" src="https://app5.shuguostar.cn/imgs/images/home/text.png" />
            <text class="title-name">
              共计阅读字数
            </text>
          </view>

          <view class="item-content flex">
            <text class="content-num">
              {{ detail?.fonts && formatPrice(detail.fonts) }}
            </text>
            <text class="content-text">
              万字
            </text>
          </view>
        </view>
        <view class="end-item item-bottom">
          <view class="item-title flex items-center">
            <image class="title-icon" src="https://app5.shuguostar.cn/imgs/images/home/read.png" />
            <text class="title-name">
              共计阅读书
            </text>
          </view>

          <view class="item-content flex">
            <text class="content-num">
              {{ detail?.books && formatPrice(detail.books) }}
            </text>
            <text class="content-text">
              本
            </text>
          </view>
        </view>

        <view class="end-btn" @click="handleDownload">
          保存图片
        </view>
      </view>
    </view>

    <view class="end-bottom flex justify-between">
      <view class="bottom-left flex flex-col">
        <text class="info1">
          这里的宣传语是什么？
        </text>
        <text class="info2">
          这里的宣传语是什么？
        </text>
        <text class="info3">
          长按识别二维码
        </text>
      </view>
      <view class="bottom-right flex">
        <text class="text">
          长按识别
        </text>
        <view class="qr-wrap">
          <image class="qr" :src="qrCodeUrl" />
        </view>
      </view>
    </view>
    <l-painter ref="painter" is-canvas-to-temp-file-path :pixel-ratio="2" path-type="url" custom-style="position: fixed; left: 200%" @success="drawDone" />
  </view>
</template>

<script setup lang="ts">
import { posterFun } from './config';
import NavigationBar from '@/components/navigation-bar/index.vue';
import { formatPrice } from '@/utils';
import { useUserStore } from '@/store';

interface Detail {
  bookName: string;
  startDate: string;
  endDate: string;
  books: string;
  fonts: string;
}

const store = useUserStore();
const detail = ref<Detail>({
  bookName: '',
  startDate: '',
  endDate: '',
  books: '',
  fonts: '',
});

// 长按识别二维码
// const previewImage = (e: any) => {
//   uni.previewImage({
//     // 需要预览的图片链接列表。若无需预览，可以注释urls
//     urls: [e.target.src],
//     // 为当前显示图片的链接/索引值
//     current: e.target.src,
//     // 图片指示器样式
//     indicator: 'default',
//     // 是否可循环预览
//     loop: false,
//     // 长按图片显示操作菜单，如不填默认为保存相册
//     // longPressActions: {
//     //   itemList: [this.l('发送给朋友'), this.l],
//     // },
//     success: (res) => {
//       console.log('previewImage res', res);
//     },
//     fail: (err) => {
//       console.log('previewImage err', err);
//     },
//   });
// };
const goBack = () => {
  uni.navigateBack({ delta: 3 });
};

const qrCodeUrl = ref<string>('');
const posterParams = {
  userName: store.userName,
  posterBg: 'linear-gradient( 90deg, #4FB0FE 0%, #2B9BF6 100%)',
  qrCodeUrl: qrCodeUrl.value,
};

const painter = ref();
// 海报绘制前处理
const handleBefore = () => {
  const poster = posterFun({ ...posterParams, ...detail.value });
  // 渲染海报
  painter.value.render(poster);
};

/**
 * 数据初始化
 */
const initData = async () => {
  uni.showLoading({ title: '画报生成中', icon: 'loading' });
  handleBefore();
};

const saveImg = (path: string) => {
  uni.saveImageToPhotosAlbum({
    filePath: path,
    success() {
      uni.hideLoading();
      uni.showToast({
        icon: 'success',
        title: '已保存到系统相册',
        duration: 1500,
      });
    },
    fail: (error) => {
      uni.hideLoading();
      uni.showToast({
        title: error.errMsg,
        icon: 'error',
        mask: true,
      });
    },
  });
};

// 海报 绘制成功
const drawDone = ($event: any) => {
  const path = $event;
  uni.hideLoading();
  // 获取用户是否开启 授权保存图片到相册。
  uni.getSetting({
    success(res) {
      // 如果没有授权
      if (!res.authSetting['scope.writePhotosAlbum']) {
        // 则拉起授权窗口
        uni.authorize({
          scope: 'scope.writePhotosAlbum',
          success() {
            // 点击允许后--就一直会进入成功授权的回调 就可以使用获取的方法了
            saveImg(path);
          },
          fail() {
            // 点击了拒绝授权后--就一直会进入失败回调函数--此时就可以在这里重新拉起授权窗口
            uni.showModal({
              title: '提示',
              content: '若点击不授权，将无法保存图片',
              cancelText: '不授权',
              cancelColor: '#999',
              confirmText: '授权',
              confirmColor: '#f94218',
              success(res) {
                if (res.confirm) {
                  // 选择弹框内授权
                  uni.openSetting({
                    success(res) {
                      console.log(res.authSetting);
                    },
                  });
                }
                else if (res.cancel) {
                  // 选择弹框内 不授权
                  console.log('用户点击不授权');
                }
              },
            });
          },
        });
      }
      else {
        // 有权限--直接保存
        console.log('有权限  直接调用相应方法');
        saveImg(path);
      }
    },
    fail: (error) => {
      console.log('调用微信的查取权限接口失败，并不知道有无权限!只有success调用成功才只知道有无权限', error);
      uni.showToast({
        title: error.errMsg,
        icon: 'none',
        duration: 1500,
      });
    },
  });
};

const handleDownload = () => {
  initData();
};

onLoad((options: any) => {
  const { bookName, startDate, endDate, books, fonts } = options;
  detail.value = {
    bookName,
    startDate,
    endDate,
    books,
    fonts,
  };
});

// 分享
uni.showShareMenu({
  withShareTicket: true,
  menus: ['shareAppMessage', 'shareTimeline'],
});
onShareAppMessage(() => {
  return {
    title: '雨果读书',
    imageUrl: 'https://app5.shuguostar.cn/imgs/images/home/share.png',
  };
});
</script>

<style lang="scss" scoped>
.end {
  position: relative;
  width: 100%;
  padding-top: 188rpx;
  min-height: 100%;
  background: linear-gradient( 90deg, #4FB0FE 0%, #2B9BF6 100%);

  .end-bg {
    position: absolute;
    top: 100rpx;
    left: 36rpx;
    width: 666rpx;
    height: 124rpx;
  }

  .end-id {
    position: absolute;
    top: 166rpx;
    right: 0;
    width: 372rpx;
    height: 430rpx;
    z-index: 1;
  }

  .end-content {
    position: relative;
    width: 670rpx;
    height: 906rpx;
    padding: 32rpx;
    margin: 168rpx 40rpx 308rpx 40rpx;

    .text-bg {
      position: absolute;
      top: 0;
      left: 0;
      width: 670rpx;
      height: 906rpx;
    }

    .end-title {
      position: relative;
      font-size: 36rpx;
      line-height: 50rpx;
      font-weight: 500;
      color: #fff;
      z-index: 1;
    }

    .end-wrap {
      position: relative;
      margin-top: 18rpx;
      width: 100%;
      height: 100%;
      padding: 32rpx;
      background: #fff;
      border-radius: 24rpx;
      z-index: 1;

      .end-info {
        padding-bottom: 16rpx;

        .label {
          font-size: 24rpx;
          line-height: 36rpx;
          color: #666;
        }

        .value {
          width: 310rpx;
          font-size: 24rpx;
          line-height: 36rpx;
          color: #333;
        }
      }

      .end-item {
        padding: 32rpx;

        .item-title {
          .title-icon {
            width: 48rpx;
            height: 48rpx;
          }

          .title-name {
            padding-left: 8rpx;
            line-height: 48rpx;
            font-size: 28rpx;
            font-weight: 500;
            color: #333;
          }
        }

        .item-content {
          padding-top: 12rpx;
          align-items: flex-end;

          .content-num {
            font-size: 48rpx;
            line-height: 68rpx;
            color: #333;
          }

          .content-text {
            padding-left: 8rpx;
            font-size: 28rpx;
            font-weight: 500;
            line-height: 64rpx;
            color: #333;
          }
        }
      }

      .item-top {
        margin-top: 24rpx;
      }

      .item-bottom {
        margin-top: 16rpx;
        margin-bottom: 40rpx;
      }

      .end-btn {
        width: 100%;
        font-size: 32rpx;
        line-height: 96rpx;
        color: #fff;
        text-align: center;
        background: #4AAAF8;
        box-shadow: 0rpx 4rpx 12rpx 0rpx #377EB8;
        border-radius: 48rpx;
      }
    }
  }

  .end-bottom {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 750rpx;
    padding: 16rpx 40rpx;
    background: #fff;

    .bottom-left {
      .info1 {
        font-size: 28rpx;
        line-height: 40rpx;
        color: #4AAAF8;
      }

      .info2 {
        margin: 16rpx 0;
        padding: 0 16rpx;
        background: linear-gradient( 90deg, #F69576 0%, #FB634E 100%);
        border-radius: 24rpx;

        font-size: 28rpx;
        font-weight: 500;
        line-height: 48rpx;
        color: #fff;
      }

      .info3 {
        font-size: 24rpx;
        line-height: 32rpx;
        color: #888888;
      }
    }

    .bottom-right {
      padding: 8rpx;
      background: linear-gradient( 180deg, #FFB196 0%, #FB634E 100%);
      border-radius: 16rpx;

      .text {
        padding: 16rpx 12rpx 16rpx 16rpx;
        width: 56rpx;
        font-size: 28rpx;
        line-height: 32rpx;
        color: #fff;
      }

      .qr-wrap {
        width: 160rpx;
        height: 160rpx;
        padding: 4rpx;
        border-radius: 8rpx;
        background: #fff;

        .qr {
          width: 100%;
          height: 100%;
          background: #CCCCCC;
          border-radius: 8rpx;
        }
      }
    }
  }
}
</style>
